const fs = require("fs");
const path = require("path");

const ENTITY_DIR = path.join("StudentVideo.Data", "Entities");
const DBSET_FILE = path.join("StudentVideo.Data", "AppDbContext.DbSet.cs");
const NAMESPACE = "namespace StudentVideo.Data;";

let context =
   "using Microsoft.EntityFrameworkCore;\n" +
   "using StudentVideo.Data.Entities;\n\n" +
   `${NAMESPACE}\n\n` +
   "public partial class AppDbContext {\n\n";

let dbsets = "";

fs.readdirSync(ENTITY_DIR).forEach(file => {
   if (!file.endsWith(".cs")) return;
   const filePath = path.join(ENTITY_DIR, file);
   const content = fs.readFileSync(filePath, "utf-8");

   // 检查是否有 [Table(
   if (!content.includes("[Table(")) return;

   // 获取类名
   const classMatch = content.match(/public\s+(?:partial\s+)?class\s+(\w+)/);
   if (!classMatch) return;
   const className = classMatch[1];

   // 提取类定义上方的 XML 注释
   let xmlComment = "";
   const lines = content.split("\n");
   for (let i = 0; i < lines.length; i++) {
      if (lines[i].trim().startsWith("///")) {
         xmlComment += "   " + lines[i].trim() + "\n";
      }

      if (/public\s+(partial\s+)?class\s+\w+/.test(lines[i])) break;
   }

   // 去除Entity后缀
   let cleanClass = className.endsWith("Entity") ? className.slice(0, -6) : className;

   // 生成DbSet属性名（简单复数规则）
   let prop = /[sS]$/.test(cleanClass) ? cleanClass : cleanClass + "s";

   // 写入 XML 注释（如果存在）
   if (xmlComment) dbsets += xmlComment;

   dbsets += `   public DbSet<${className}> ${prop} { get; set; }\n\n`;
});

context += dbsets;
context += "}\n";

fs.writeFileSync(DBSET_FILE, context, "utf-8");
console.log(`已生成 ${DBSET_FILE}`);
